<template>
  <view class="container">
    <!-- 表单内容 -->
    <u-form class="form-content">
      <!-- 身份证号输入 -->
      <u-form-item label="请输入身份证号" class="form-item" label-width="120">
        <u-input
          v-model="formData.idcertnum"
          placeholder="请输入身份证号"
          class="custom-input"
        />
      </u-form-item>

      <dynamic-inputs
        ref="dynamicInputs"
        :inputConfigs="inputConfigs1"
        @input-change="handleInputChange"
        :label="label"
        :idcertnum="formData.idcertnum"
        :checkIdcertnum="true"
      ></dynamic-inputs>

      <!-- 资格证初领日期输入 -->
      <u-form-item label="资格证初领日期" class="form-item" label-width="120">
        <up-datetime-picker
          ref="datetimePickerRef"
          hasInput
          :show="showDate"
          @close="showDate = false"
          v-model="formData.qualificationStartDate"
          placeholder="请选择资格证初领日期"
          mode="date"
          :formatter="formatter"
        ></up-datetime-picker>
      </u-form-item>
    </u-form>

    <!-- 查询按钮 -->
    <view class="btn-container">
      <u-button @click="submitForm">立即查询</u-button>
    </view>
  </view>
</template>

<script>
// import areaPicker from "@/components/area-picker/area-picker.vue";
import DynamicInputs from "@/components/area-pickerselect/dynamicInputs.vue";

import {
  getWorkType,
  getPersonneScore,
} from "@/common/api/hub_zsyg/trans/queryPracscore.js";
export default {
  components: {
    DynamicInputs,
  },
  data() {
    return {
      inputConfigs1: [
        {
          placeholder: "选择从业资格类型",
          functionName: "getWorkType",
          label: "从业资格证书",
          value: "practypecodes",
        },
      ],
      title: "选择从业资格类型",
      datetimePickerRef: null,

      formData: {
        idcertnum: "421087198208241316", // 身份证号
        qualification: "", // 从业资格类型
        qualificationStartDate: Date.now(), // 从业资格时间
      },

      showDate: false, // 起止时间选择
    };
  },

  methods: {
    formatter(type, value) {
      if (type === "year") {
        return `${value}年`;
      }
      if (type === "month") {
        return `${value}月`;
      }
      if (type === "day") {
        return `${value}日`;
      }
      return value;
    },
    // 更新选择器范围
    updatePickerRange(data, index) {
      console.log(`更新选择器范围，索引: ${index}`, data);
      if (Array.isArray(data)) {
        this.$set(this.localInputConfigs[index], "data", data);
        const labels = data.map((item) => item.label);
        this.columns = [labels];
      } else {
        console.error(`updatePickerRange: 接收到的数据不是数组`, data);
        this.columns = [[]];
      }
    },
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      return `${year}-${month}-${day}`;
    },

    getWorkType() {
      if (!this.formData.idcertnum) {
        uni.showToast({
          title: "请输入身份证号",
          icon: "none",
        });
        return;
      }

      const params = {
        idcertnum: this.formData.idcertnum,
      };
      getWorkType(params)
        .then((res) => {
          console.log(res.data.data[0], "从业资格类型数据");
          const pcData = res.data.data[0].pc;
          let formattedData;

          // 检查 pcData 是否为数组
          if (Array.isArray(pcData)) {
            formattedData = pcData.map((item) => ({
              label: item.practypenames,
              value: item.practypecodes,
            }));
          } else if (typeof pcData === "object") {
            // 如果 pcData 是一个对象，将其转换为数组
            formattedData = [
              {
                label: pcData.practypenames,
                value: pcData.practypecodes,
              },
            ];
          } else {
            console.error("Unexpected pcData format:", pcData);
            formattedData = [];
          }

          console.log("格式化后的数据:", formattedData);

          // 更新 inputConfigs1 中的数据
          this.$set(this.inputConfigs1[0], "data", formattedData);

          // 触发 dynamicInputs 组件的更新
          this.$nextTick(() => {
            this.$refs.dynamicInputs.updateData(formattedData);
          });
        })
        .catch((error) => {
          console.error("获取从业资格类型失败:", error);
        });
    },
    // 确认选择
    confirm(e) {
      const selectedLabel = e.value[0];
      const currentConfig = this.localInputConfigs[this.currentInputIndex];
      const selectedItem = currentConfig.data.find(
        (item) => item.label === selectedLabel
      );
      this.$set(currentConfig, "selectedValue", selectedLabel);
      this.show = false;
      console.log(
        "已选择:",
        selectedLabel,
        "函数名:",
        currentConfig.functionName,
        "完整数据:",
        selectedItem
      );

      this.$emit("input-change", {
        index: this.currentInputIndex,
        value: selectedItem,
        functionName: currentConfig.functionName,
      });
    },
    // 打开从业资格类型选择器
    handleInputChange(data) {
      if (data.functionName === "getWorkType") {
        if (!this.formData.idcertnum) {
          uni.showToast({
            title: "请输入身份证号",
            icon: "none",
          });
          return;
        }
        this.getWorkType();
      }
    },

    submitForm() {
      const date = new Date(this.formData.qualificationStartDate);
      const formattedDate = this.formatDate(date); // 使用自定义格式化方法

      const params = {
        idcertnum: this.formData.idcertnum, // 身份证号
        praccertfirstdate: formattedDate, // 格式化后的日期
        practypecodes: "09002", // 从业资格类型代码
        page: 1, // 页码
        pagesize: 10, // 每页大小
      };
      getPersonneScore(params).then((res) => {
        if (res.data.totals > 0) {
          // 如果有数据，跳转到查询结果页面
          uni.navigateTo({
            url: "/pages/hub_zsyg/trans/queryPracscoreInfo",
          });
        } else {
          // 如果没有数据，显示提示信息
          uni.showToast({
            title: "无该从业人员的记分信息，请检查输入是否有误",
            icon: "none",
          });
        }
      });
    },
  },
};
</script>

<style scoped lang="scss">
.container {
  padding: 10px;
  background-color: #f3f6fa;
  height: 100vh;
  box-sizing: border-box;
}

.form-content {
  background-color: #ffffff;
  padding: 0;
  /* 去掉 padding */
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  ::v-deep uni-view.u-input.u-border.u-input--radius.u-input--square {
    border: none;
  }
}

// .form-item {
//   padding: 0 10px;
//   border-bottom: 1px solid #f1f1f1;
//   color: #0d1444;
//   font-size: 16px;
//   /* 设置下边框 */
//   ::v-deep .u-border,
//   .up-border {
//     border: none !important;
//   }
// }
::v-deep .u-form-item {
  padding: 0 10px !important;
  border-bottom: 1px solid #f1f1f1;
}

.form-item {
  padding: 0 10px;
  border-bottom: 1px solid #f1f1f1;

  /* 设置下边框 */
  ::v-deep .u-border,
  .up-border {
    border: none !important;
  }
}

.custom-input {
  border: none;
  /* 去掉输入框的边框 */
  background-color: transparent;
  /* 使背景透明 */
}

.btn-container {
  margin-top: 30px;
  text-align: center;
  // position: absolute;
  // bottom: 20px;
  // right: 0;

  width: 100%;
  box-sizing: border-box;
  ::v-deep .u-button--info[data-v-461e713c] {
    width: 100%;
    background-color: #2877ff;
    color: #ffffff;
  }
}

.arrow-icon-groud {
  position: relative;
  flex: 1;

  .arrow-icon {
    position: absolute !important;
    right: 20px;
    top: 10px;
  }
}
</style>
